# listings/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser, Skill, Need

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'email', 'user_type', 'student_id', 'college', 'major', 'bio')
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 移除默认的帮助文本
        for field in self.fields.values():
            field.help_text = None
        
        # 自定义字段标签和提示文本
        self.fields['username'].label = '用户名'
        self.fields['username'].widget.attrs.update({
            'placeholder': '请输入3-20位字符的用户名',
            'class': 'form-control'
        })
        
        self.fields['password1'].label = '密码'
        self.fields['password1'].widget.attrs.update({
            'placeholder': '请输入至少8位的密码',
            'class': 'form-control'
        })
        
        self.fields['password2'].label = '确认密码'
        self.fields['password2'].widget.attrs.update({
            'placeholder': '请再次输入密码',
            'class': 'form-control'
        })
        
        self.fields['email'].label = '电子邮箱'
        self.fields['email'].required = True
        self.fields['email'].widget.attrs.update({
            'placeholder': '请输入有效的电子邮箱地址',
            'class': 'form-control'
        })
        
        self.fields['user_type'].label = '用户类型'
        self.fields['user_type'].widget.attrs.update({
            'class': 'form-select'
        })
        
        self.fields['student_id'].label = '学号/工号'
        self.fields['student_id'].required = True
        self.fields['student_id'].widget.attrs.update({
            'placeholder': '请输入学号或工号',
            'class': 'form-control'
        })
        
        self.fields['college'].label = '学院'
        self.fields['college'].required = True
        self.fields['college'].widget.attrs.update({
            'placeholder': '请输入所属学院',
            'class': 'form-control'
        })
        
        self.fields['major'].label = '专业/部门'
        self.fields['major'].required = True
        self.fields['major'].widget.attrs.update({
            'placeholder': '请输入专业或所属部门',
            'class': 'form-control'
        })
        
        self.fields['bio'].label = '个人简介'
        self.fields['bio'].required = False
        self.fields['bio'].widget.attrs.update({
            'placeholder': '请简单介绍一下自己（选填）',
            'class': 'form-control',
            'rows': 3
        })

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email:
            if CustomUser.objects.filter(email=email).exists():
                raise forms.ValidationError('该邮箱已被注册')
        return email

    def clean_student_id(self):
        student_id = self.cleaned_data.get('student_id')
        if student_id:
            if CustomUser.objects.filter(student_id=student_id).exists():
                raise forms.ValidationError('该学号/工号已被注册')
        return student_id

class CustomUserChangeForm(UserChangeForm): # 用于在 Admin 或用户编辑自己信息时
    class Meta(UserChangeForm.Meta):
        model = CustomUser
        fields = ('username', 'email', 'first_name', 'last_name', 'user_type', 'student_id', 'college', 'major', 'bio', 'is_active', 'is_staff') # 注意密码不在这里直接修改

class SkillForm(forms.ModelForm):
    class Meta:
        model = Skill
        fields = ['title', 'description', 'category', 'reward_type', 'reward_description', 'tags']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 4}),
            'reward_description': forms.TextInput(attrs={'placeholder': '例如：免费帮助/期望交换XX技能/XX积分等'}),
            'tags': forms.TextInput(attrs={'placeholder': '用逗号分隔多个标签'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['title'].label = '技能标题'
        self.fields['description'].label = '技能描述'
        self.fields['category'].label = '技能分类'
        self.fields['reward_type'].label = '回报方式'
        self.fields['reward_description'].label = '回报说明'
        self.fields['tags'].label = '标签'

class NeedForm(forms.ModelForm):
    class Meta:
        model = Need
        fields = ['title', 'description', 'category', 'reward_type', 'reward_description', 'tags']
        widgets = {
            'description': forms.Textarea(attrs={'rows': 4}),
            'reward_description': forms.Textarea(attrs={'rows': 3}),
            'tags': forms.TextInput(attrs={'placeholder': '用空格分隔多个标签'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['title'].label = '需求标题'
        self.fields['description'].label = '需求描述'
        self.fields['category'].label = '需求分类'
        self.fields['reward_type'].label = '回报方式'
        self.fields['reward_description'].label = '回报说明'
        self.fields['tags'].label = '标签'